LotteryWheel.tsx 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. "use client";
  2. import { useRef, useEffect, useState } from 'react';
  3. import styles from "./style.module.scss";
  4. const Lottery = () => {
  5. const canvasRef = useRef<any>(null);
  6. const [isSpinning, setIsSpinning] = useState(false);
  7. const [prize, setPrize] = useState('');
  8. const segments = ['一等奖', '二等奖', '三等奖', '四等奖', '五等奖', '六等奖', '七等奖', '八等奖'];
  9. // 4:1940,8:2120
  10. const segmentAngle = (2 * Math.PI) / segments.length;
  11. const drawWheel = () => {
  12. const canvas = canvasRef.current;
  13. const ctx = canvas.getContext('2d');
  14. const radius = canvas.width / 2;
  15. // 绘制背景图
  16. const backgroundImage = new Image();
  17. backgroundImage.src = '/wheel/spinBg.png'; // 替换为你的背景图路径
  18. backgroundImage.onload = () => {
  19. ctx.clearRect(0, 0, canvas.width, canvas.height);
  20. ctx.drawImage(backgroundImage, 0, 0, canvas.width, canvas.height); // 绘制背景图
  21. ctx.save();
  22. ctx.translate(radius, radius);
  23. // 绘制奖项文本
  24. segments.forEach((segment, index) => {
  25. ctx.save();
  26. ctx.rotate(index * segmentAngle);
  27. ctx.fillStyle = '#fff'; // 文字颜色
  28. ctx.font = '16px Arial';
  29. ctx.fillText(segment, radius / 2, 8); // 适当调整位置
  30. ctx.restore();
  31. });
  32. ctx.restore();
  33. };
  34. };
  35. const spinWheel = () => {
  36. if (isSpinning) return;
  37. setIsSpinning(true);
  38. let rotation = 0;
  39. const spinDuration = 5000; // 旋转持续时间
  40. const stopAngle = Math.floor(Math.random() * segments.length) * (360 / segments.length) + 360 * 5; // 随机停下的角度
  41. const spinAnimation = (timestamp:any) => {
  42. rotation += 10; // 每次增加的角度
  43. canvasRef.current.style.transform = `rotate(${rotation}deg)`;
  44. if (rotation < stopAngle) {
  45. requestAnimationFrame(spinAnimation);
  46. } else {
  47. setIsSpinning(false);
  48. const winningSegment = Math.floor(((stopAngle % 360) / (360 / segments.length)));
  49. setPrize(segments[winningSegment]);
  50. }
  51. };
  52. requestAnimationFrame(spinAnimation);
  53. };
  54. useEffect(() => {
  55. drawWheel();
  56. }, []);
  57. return (
  58. <>
  59. <img src="/wheel/draw.png" className={`${styles.drawImg} ${styles.position}`} onClick={spinWheel}/>
  60. <div className={styles.drawContents}>
  61. <canvas ref={canvasRef} id={styles.draw} width={306} height={306} />
  62. </div>
  63. {/* <button onClick={spinWheel} disabled={isSpinning}>
  64. {isSpinning ? '正在抽奖...' : '抽奖'}
  65. </button> */}
  66. {/* {prize && <h2>恭喜您,中奖:{prize}</h2>} */}
  67. </>
  68. );
  69. };
  70. export default Lottery;